import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Card,
  Row,
  Col,
  Input,
  Button,
  Cascader,
} from 'antd';

import RechargeInfo from './components/RechargeInfo';
import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { Item } = Form;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  rechargelist: any;
  INITINFO: any;
  screen: string;
}

interface TableListState {
  visible: boolean;
  current: number;
  pageSize: number | undefined;
  searchValues: any;
  formValues: any;
  rowId:number;
}

function mapStateToProps(state: any) {
  const {
    rechargeMoney: { rechargelist },
    common: { INITINFO },
    global: { screen },
    loading,
  } = state;

  return {
    rechargelist,
    INITINFO,
    screen,
    loading: loading.effects['rechargeMoney/fetch'],
  };
}

@connect(mapStateToProps)
class TableList extends React.Component<TableListProps, TableListState> {
  columns = [
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
    },
    {
      title: '合作商',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '账户余额(元)',
      dataIndex: 'consume',
      render: (text: number) => text / 100,
    },
    {
      title: '操作',
      render: (text: any, record: any) => (
        <div>
          <span
            onClick={this.handleChangeModal.bind(this, true, record)}
            className="operLink"
          >
            充值
          </span>
        </div>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    searchValues: {},
    visible: false,
    formValues: {
      fcs_id: 0,
      fcs_name: '',
      amount: 0,
    },
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...searchValues } = query;

    return {
      ...state,
      searchValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { rechargelist } = this.props;
    if (rechargelist?.list?.length) return;

    this.fetchRechargeList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, current, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchRechargeList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  }

  // 获取数据
  fetchRechargeList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchAddressList' });
    dispatch({
      type: 'rechargeMoney/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const {
      searchValues: { area_code, ...params },
      current,
      pageSize,
    } = this.state;

    if (area_code && area_code.length) {
      [params['org1.area_code'], params['org2.area_code'], params['org3.area_code']] = area_code;
    }
    params.pageNum = current;
    params.numPerPage = pageSize;

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '合作商充值',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商充值',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 查看充值记录
   */
  handleRecords = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '充值记录',
      url: '/partner/rechargeMoney/list/records',
    });
  }

  /**
   * 查看消费明细
   */
  handleConsumption = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '消费明细',
      url: '/partner/rechargeMoney/list/consumption',
    });
  }

  /**
   * 充值
   */
  handleChangeModal = (visible: boolean, record?: any) => {
    if (record) {
      const { fcs_id, name: fcs_name } = record;
      this.setState({
        formValues: { fcs_id, fcs_name, amount: 0 },
      });
    }
    this.setState({ visible });
  }

  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const { dispatch } = this.props;
    const query = { ...formValues, page, psize };

    addTab(dispatch, {
      name: '合作商充值',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, params = {}) => {
    if (typeName === 'orderStatus') { // 查询订单状态后重载当前页
      const { searchValues } = this.state;
      params = { orderValues: params, searchValues };
    }

    const type = typeName.indexOf('common') >= 0
      ? typeName : `rechargeMoney/${typeName}`;

    const { dispatch } = this.props;
    dispatch({
      type,
      payload: params,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { addressList },
    } = this.props;

    return (
      <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSearch}>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="商户名称" colon={false}>
              {getFieldDecorator('fcs_name')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="手机号码" colon={false}>
              {getFieldDecorator('phone')(
                <Input allowClear type="number" placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　省市区" colon={false}>
              {getFieldDecorator('area_code')(
                <Cascader
                  changeOnSelect
                  options={addressList}
                  placeholder="请选择"
                />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      visible,
      current,
      pageSize,
      formValues,
    } = this.state;
    const {
      rechargelist,
      loading,
    } = this.props;

    const pagination: object = rechargelist
      ? {
        total: rechargelist ? rechargelist.count : 0,
        pageSize,
        current,
        onChange: this.onSelectChange,
        showTotal: () => `共${rechargelist.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
        showQuickJumper: true,
      }
      : {};

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleRecords}
            >
              充值记录
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleConsumption}
            >消费明细
            </Button>
          </div>
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            loading={loading}
            columns={this.columns}
            dataSource={rechargelist.list || []}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <RechargeInfo
          visible={visible}
          formValues={formValues}
          fetchAction={this.fetchAction.bind(this)}
          changeModal={this.handleChangeModal.bind(this)}
        />
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
